package com.atguigu.flink0624.chapter08;

import com.atguigu.flink0624.bean.HotItem;
import com.atguigu.flink0624.bean.UserBehavior;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Comparator;
import java.util.TreeSet;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/16 15:43
 */
public class Flink03_Project_High_TopN_1 {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        env
            .readTextFile("input/UserBehavior.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new UserBehavior(Long.valueOf(data[0]),
                                        Long.valueOf(data[1]),
                                        Integer.valueOf(data[2]),
                                        data[3],
                                        Long.parseLong(data[4]) * 1000);
            })
            .filter(ub -> "pv".equals(ub.getBehavior()))
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ub, ts) -> ub.getTimestamp())
            )
            .keyBy(UserBehavior::getItemId)
            .window(SlidingEventTimeWindows.of(Time.hours(3), Time.minutes(60)))
            .aggregate(
                new AggregateFunction<UserBehavior, Long, Long>() {
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }
                    
                    @Override
                    public Long add(UserBehavior value, Long acc) {
                        return acc + 1;
                    }
                    
                    @Override
                    public Long getResult(Long acc) {
                        return acc;
                    }
                    
                    @Override
                    public Long merge(Long a, Long b) {
                        return a + b;
                    }
                },
                new ProcessWindowFunction<Long, HotItem, Long, TimeWindow>() {
                    @Override
                    public void process(Long itemId,
                                        Context ctx,
                                        Iterable<Long> elements,
                                        Collector<HotItem> out) throws Exception {
                        out.collect(new HotItem(itemId, elements.iterator().next(), ctx.window().getEnd()));
                    }
                }
            )
            .keyBy(HotItem::getWEnd)
            .process(new KeyedProcessFunction<Long, HotItem, String>() {
                
                private ValueState<TreeSet<HotItem>> setState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    
                    setState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<TreeSet<HotItem>>("setState",
                                                                             TypeInformation.of(new TypeHint<TreeSet<HotItem>>() {})));
                }
                
                @Override
                public void processElement(HotItem hotItem,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    
                    if (setState.value() == null) {
                        //1. 创建set和
                        TreeSet<HotItem> set = new TreeSet<>(new Comparator<HotItem>() {
                            @Override
                            public int compare(HotItem o1, HotItem o2) {
                                int r = o2.getCount().compareTo(o1.getCount());
                                return r == 0 ? 1 : r;
                            }
                        });
                        setState.update(set);
    
                        // 2. 注册定时器
                        ctx.timerService().registerEventTimeTimer(hotItem.getWEnd() + 5000);
                    }
                    
                    // 把数据存储到set集合中
                    TreeSet<HotItem> set = setState.value();
                    set.add(hotItem);
    
                    if (set.size() == 4) {
                       set.pollLast(); // 删除最后一个元素
                    }
    
//                    setState.update(set);
                }
                
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    TreeSet<HotItem> set = setState.value();
                    String msg = "------------\n";
    
                    for (HotItem hotItem : set) {
                        msg += hotItem + "\n";
                    }
    
                    out.collect(msg);
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
